<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;

class LoginAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // 后置中间件
        // $response = $next($request);

        // 前置中间件
        // return $next($request);

        // 后置中间件返回请求对象
        // return $response;

        /* 
            写前置中间件

            登录验证是请求前需要完成
        */

        $LoginUser = Cookie::get('LoginUser') ? json_decode(Cookie::get('LoginUser'),true) : [];

        if(empty($LoginUser))
        {
            return redirect()->route('error',['msg' => '请先登录','url' => url('home/user/login')]);
        }

        // 获取用户id
        $userid = !empty($LoginUser['id']) ? $LoginUser['id'] : 0;
        
        // 查询用户表里是否存在该用户
        $User = DB::table('user')->find($userid);

        if(!$User)
        {
            Cookie::queue(Cookie::forget('LoginUser'));
            return redirect()->route('error',['msg' => '非法登录','url' => url('home/user/login')]);
        }

        // 封装中间件的赋值数据
        // $data = [
        //     'id' => $User->id,
        //     'nickname' => $User->nickname
        // ];

        // 把登录用户信息给使用该中间件的路由
        // $request->attributes->add(['LoginUser' => $data]);

        return $next($request);
    }
}
